"use client";

import CustomSelect from "@/components/select/select";
import useCategories from "@/app/hooks/categories.hook";
import { useEffect, useState } from "react";
import itemsService from "@/app/services/items.service";
import Item, { ItemCategory } from "@/shared/item";
import FileUploader from "@/components/photo-uploader/page";
import { useNotifications } from "@/app/hooks/notification.hook";
import MyLineChart from "@/components/chart/chart";
import { useRouter } from "next/navigation";

export default function ManageIdPage({ params }: { params: { id: number } }) {
  const router = useRouter();
  const { showError, showSuccess } = useNotifications();
  const [loading, setLoading] = useState(true);
  const [selectedFile, setSelectedFile] = useState<File | null>(null);
  const { categories } = useCategories();
  const [item, setItem] = useState<
    | (Item & { category: ItemCategory; stat: { [key: string]: number }[] })
    | null
  >(null);

  useEffect(() => {
    const l = async () => {
      const item = await itemsService.getItemById(params.id);

      setItem(item);
      setLoading(false);
    };

    l();
  }, []);

  if (loading)
    return (
      <section className="manage" style={{ flex: 2 }}>
        <span className="loader"></span>
      </section>
    );

  const handleChange = (e: React.FormEvent<HTMLInputElement>) => {
    setItem((prev) => {
      return { ...prev, [e.target.name]: e.target.value };
    });
  };

  const handleSubmit = async () => {
    try {
      await itemsService.updateItemById(
        params.id,
        item!,
        selectedFile ?? undefined
      );
      showSuccess("Информация успешно обновлена");
    } catch {
      showError("Ошибка при обновлении информации");
    }
  };

  const handleDelete = async () => {
    try {
      await itemsService.deleteItem(item!.id);
      showSuccess("Позиция успешно удалена");
      router.push("/manage");
    } catch {
      showError("Ошибка при удалении позиции");
    }
  };

  return (
    <section className="manage" style={{ flex: 2 }}>
      <h1 className="heading">
        <span>Информация</span>
      </h1>
      <div className="row">
        <div className="info">
          <div className="row">
            <div className="item f1">
              <span>Фото:</span>
              <FileUploader
                setSrc={(src) => {
                  setSelectedFile(src);
                }}
                src={item!.photo}
              />
            </div>
            <div className="col f1">
              <div className="item">
                <span>Наименование:</span>
                <div className="inputBox">
                  <span className="fa  fa-asterisk"></span>
                  <input
                    type="text"
                    value={item?.name}
                    placeholder="Наименование"
                    name="name"
                    onChange={handleChange}
                  />
                </div>
              </div>
              <div className="item">
                <span>Категория:</span>
                <CustomSelect
                  placeholder={item?.category.name}
                  options={categories.map((cat) => ({
                    label: cat.name,
                    value: cat.id,
                  }))}
                  onChange={(val) => {
                    setItem((prev) => ({
                      ...prev,
                      categoryId: val,
                    }));
                  }}
                />
              </div>
            </div>
          </div>
          <div className="row">
            <div className="item">
              <span>Описание:</span>
              <div className="inputBox">
                <span className="fas fa-font"></span>
                <input
                  value={item?.description}
                  type="text"
                  placeholder="Описание"
                  onChange={handleChange}
                  name="description"
                />
              </div>
            </div>
          </div>
          <div className="row">
            <div className="item">
              <span>Стоимость:</span>
              <div className="inputBox">
                <span className="fa fa-rub"></span>
                <input
                  type="text"
                  value={item?.price}
                  placeholder="Стоимость"
                  onChange={(e) => {
                    if (Number.parseFloat(e.target.value)) handleChange(e);
                  }}
                  name="price"
                />
              </div>
            </div>
          </div>
          <div className="row">
            <input
              style={{
                width: "50%",
                margin: "10px auto",
                backgroundColor: "tomato",
              }}
              type="submit"
              onClick={handleDelete}
              value="Удалить"
              className="btn"
            />
            <input
              style={{
                width: "50%",
                margin: "10px auto",
              }}
              type="submit"
              onClick={handleSubmit}
              value="Сохранить"
              className="btn"
            />
          </div>
        </div>
        <div className="row">
          <div className="item">
            <span>Заказы за последний год:</span>
            <div className="inputBox" style={{ border: "none" }}>
              <MyLineChart
                labels={Object.keys(item!.stat)}
                data={Object.keys(item!.stat).map((k) => item!.stat[k])}
              />
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}
